package netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.apache.log4j.Logger;

import java.util.List;

public class ProtocolDecoder extends ByteToMessageDecoder {

    private Logger logger = Logger.getLogger(ProtocolHeader.class);

    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
            throws Exception {
        if (in.readableBytes() < ProtocolHeader.HEADER_LENGTH) {
            logger.info("数据包长度小于协议头长度");
            return;
        }
        in.markReaderIndex();

        if (in.readShort() != ProtocolHeader.MAGIC) {
            logger.info("Magic不一致");
            in.resetReaderIndex();
            return;
        }

        byte sign = in.readByte();
        byte type = in.readByte();
        byte status = in.readByte();

        int bodyLength = in.readInt();
        if (in.readableBytes() != bodyLength) {
            logger.info("消息体长度不一致");
            in.resetReaderIndex();
            return;
        }

        byte[] bytes = new byte[bodyLength];
        in.readBytes(bytes);

        MessageHolder messageHolder = new MessageHolder();
        messageHolder.setSign(sign);
        messageHolder.setStatus(status);
        messageHolder.setType(type);
        messageHolder.setBody(new String(bytes, "utf-8"));

        out.add(messageHolder);
    }
}
